﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using Itasa.API;
using Itasa.RSS;
using System.Xml;
using System.Net;
using System.IO;

namespace Itasa
{
    /// <summary>
    /// Logica di interazione per MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private int SubsRows = 0;
        private bool firstUpdate = true;
        private DateTime LastUpdate;

        public MainWindow()
        {
            InitializeComponent();
            Params.mW = this;
            Config.loadConfig();
            Params.dm_t = new Thread(Params.dm.ThreadMain);
            Params.dm_t.Start();
            Params.user = ITASA_API.login(Config.ITASAusr, Config.ITASApwd);
            
            if (Config.IsCalendar) Params.Calendario = new Calendar(Params.user);
        }

        internal void windowButton()
        {
            dl_myITASA.IsEnabled = Config.IsMyItasa;
            dl_myITASA_new.IsEnabled = Config.IsMyItasa;
            dl_ITASA.IsEnabled = Config.IsItasa;
        }

        protected override void OnStateChanged(EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
                this.Hide();

            base.OnStateChanged(e);
        }

        private void Config_Click(object sender, RoutedEventArgs e)
        {
            Params.cfg = new Config();
            Params.cfg.Show();
        }

        private void Window_Closing(object sender, EventArgs e)
        {
            System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
            ni.Visible = false;
            ni.Icon = null;
            ni.Dispose();
            Params.dm_t.Abort();
            if (Params.updater.IsAlive) Params.updater.Abort();
            if (Params.logUpdater.IsAlive) Params.logUpdater.Abort();
            Config.saveConfig();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
            ni.Text = "ItaSA RSS2SUB";
            ni.Icon = new System.Drawing.Icon(Itasa.Properties.Resources.logofbico, Itasa.Properties.Resources.logofbico.Size);
            System.Windows.Forms.ContextMenu m_menu = new System.Windows.Forms.ContextMenu();
            m_menu.MenuItems.Add(0, new System.Windows.Forms.MenuItem("Scarica Nuovi", new System.EventHandler(DlNew_Click)));
            m_menu.MenuItems.Add(1, new System.Windows.Forms.MenuItem("Update", new System.EventHandler(Update_Click)));
            m_menu.MenuItems.Add(2, new System.Windows.Forms.MenuItem("Scarica Ultimi", new System.EventHandler(DlLatest_Click)));
            m_menu.MenuItems.Add(3, new System.Windows.Forms.MenuItem("-"));
            m_menu.MenuItems.Add(4, new System.Windows.Forms.MenuItem("Mostra", new System.EventHandler(Mostra_Click)));
            m_menu.MenuItems.Add(5, new System.Windows.Forms.MenuItem("Nascondi", new System.EventHandler(Nascondi_Click)));
            m_menu.MenuItems.Add(6, new System.Windows.Forms.MenuItem("-"));
            m_menu.MenuItems.Add(7, new System.Windows.Forms.MenuItem("Esci", new System.EventHandler(Esci_Click)));
            ni.ContextMenu = m_menu;
            ni.Visible = true;
            ni.DoubleClick +=
                delegate(object sender2, EventArgs args)
                {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                };
            if (Params.updater != null && Params.updater.IsAlive) Params.updater.Abort();
            Params.updater = new Thread(updaterLoop);
            Params.updater.Start();
            if (Params.logUpdater != null && Params.logUpdater.IsAlive) Params.logUpdater.Abort();
            Params.logUpdater = new Thread(updateLog);
            Params.logUpdater.Start();
            if (Config.HideStart) this.Hide();
        }

        protected void DlLatest_Click(Object sender, System.EventArgs e)
        {
            downloadLatest(true);
        }

        protected void DlNew_Click(Object sender, System.EventArgs e)
        {
            downloadNew();
        }

        protected void Update_Click(Object sender, System.EventArgs e)
        {
            Params.updater.Interrupt();
        }

        protected void Mostra_Click(Object sender, System.EventArgs e)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
        }

        protected void Esci_Click(Object sender, System.EventArgs e)
        {
            this.Close();
        }

        protected void Nascondi_Click(Object sender, System.EventArgs e)
        {
            this.Hide();
        }

        private void updateLog()
        {
            while (true)
            {
                if (Params.logStack.IsEmpty) Params.logStack_event.WaitOne();
                if (this.Dispatcher.CheckAccess())
                {
                    String text;
                    while (Params.logStack.TryPop(out text))
                    {
                        this.logText.Text = DateTime.Now.ToLongTimeString() + " - " + text + "\n" + this.logText.Text;
                    }
                }
                else
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate()
                    {
                        String text;
                        while (Params.logStack.TryPop(out text))
                        {
                            this.logText.Text = DateTime.Now.ToLongTimeString() + " - " + text + "\n" + this.logText.Text;
                        }
                    });
                }
            }
        }

        private void updateProgressBar(double i, String txt)
        {
            this.updateProgress.Value = i;
            this.lupdateProgress.Content = txt;
        }

        private void toggleIndeterminateProgressBar()
        {
            if (this.updateProgress.IsIndeterminate) this.updateProgress.IsIndeterminate = false;
            else this.updateProgress.IsIndeterminate = true;
        }

        private void updaterLoop()
        {
            while (true)
            {
                Params.Dispatch(this, toggleIndeterminateProgressBar);
                if (Config.IsMyItasa)
                {
                    Params.Dispatch(this, updateProgressBar, 0, "Ricezione dati serie preferite...");
                    updateMyShows();
                    Params.Dispatch(this, updateProgressBar, 0, "Ricezione dati rss sottotitoli serie preferite...");
                    updateMyRSS();
                    Params.Dispatch(this, updateMyRSSTab);
                    if (Config.IsTorrent)
                    {
                        Params.Dispatch(this, updateProgressBar, 0, "Ricezione dati torrents serie preferite...");
                        updateTorrentXML();
                        Params.Dispatch(this, updateTorrentTab);
                    }
                }
                if (Config.IsCalendar)
                {
                    Params.Dispatch(this, updateProgressBar, 0, "Elaborazione dati calendario...");
                    updateCalendarioXML();
                    Params.Dispatch(this, updateCalendario);
                }
                if (Config.IsItasa)
                {
                    Params.Dispatch(this, updateProgressBar, 0, "Ricezione dati rss sottotitoli...");
                    updateItasaRSS();
                    Params.Dispatch(this, updateItasaRSSTab);
                }
                Params.Dispatch(this, toggleIndeterminateProgressBar);
                if (Config.IsMyItasa)
                {
                    if (Config.Additional)
                    {
                        Params.Dispatch(this, updateProgressBar, 0, "Ricezione dati sottotitoli serie preferite...");
                        updateMySubs();
                    }
                    Params.Dispatch(this, updateMyShowsTab);
                }
                Params.Dispatch(this, updateProgressBar, 100, "Ricezione Completata");
                if (Config.IsAutoDl) downloadNew();
                firstUpdate = false;
                try
                {
                    Thread.Sleep(Params.updatems);
                }
                catch (ThreadInterruptedException) { }
            }
        }

        private void downloadLatest(bool forced)
        {
            if (Params.myITASA != null)
            {
                if (firstUpdate)
                {
                    foreach (RSS_Sub rs in Params.myITASA)
                    {
                        if (!File.Exists(Params.getFilePath(rs.SubInfo))) Params.dm.downloadSub(rs.SubInfo);
                        else if (!forced) break;
                    }
                    LastUpdate = DateTime.Now;
                }
                else
                {
                    foreach (RSS_Sub rs in Params.myITASA)
                    {
                        if (rs.PubDate >= LastUpdate && !File.Exists(Params.getFilePath(rs.SubInfo))) Params.dm.downloadSub(rs.SubInfo);
                    }
                    LastUpdate = DateTime.Now;
                }
            }
        }

        private void downloadNew()
        {
            if (Params.LastSubs != null && Config.Additional)
            {
                foreach (Sub s in Params.LastSubs)
                {
                    if (s.DownloadDate.Count == 0)
                    {
                        Params.dm.downloadSub(s.SubInfo);
                        s.DownloadDate.Add(DateTime.Now);
                    }
                    else break;
                }
            }
            else downloadLatest(false);
        }

        #region SEZIONE TAB MYSHOWS

        private void updateMyShows()
        {
            if (Params.Shows == null) Params.Shows = new List<Show>();
            List<Show> ls = ITASA_API.favShows(Params.user);
            foreach (Show s in ls)
            {
                if (!Params.Shows.Contains(s)) Params.Shows.Add(s);
                else Params.SearchShow(s.ID).ChangeEpisodes(s);
            }
        }

        private void updateMyShowsTab()
        {
            if (Params.Shows != null)
            {
                Params.Shows.Sort();
                showsRoot.Items.Clear();
                foreach (Show s in Params.Shows)
                {
                    TreeViewItem tvis = new TreeViewItem();
                    tvis.Header = s.Name;
                    tvis.ToolTip = new ShowTooltip(s);
                    tvis.ContextMenu = Show_ContextMenu(s);
                    showsRoot.Items.Add(tvis);
                    foreach (Itasa.API.Version v in s.Versions)
                    {
                        TreeViewItem tviv = new TreeViewItem();
                        tviv.Header = v.VersionName;
                        tvis.Items.Add(tviv);
                        tviv.ToolTip = "Fai Doppio Click per scaricare tutti i sottotitoli della versione";
                        tviv.MouseDoubleClick += new MouseButtonEventHandler(versionTVI_MouseDoubleClick);
                        foreach (Season se in v.Seasons)
                        {
                            TreeViewItem tvise = new TreeViewItem();
                            tvise.Header = "Stagione " + se.SeasonNumber;
                            tviv.Items.Add(tvise);
                            tvise.ToolTip = "Fai Doppio Click per scaricare tutti i sottotitoli della stagione";
                            tvise.MouseDoubleClick += new MouseButtonEventHandler(seasonTVI_MouseDoubleClick);
                            foreach (Sub su in se.Subs)
                            {
                                TreeViewItem tvisu = new TreeViewItem();
                                tvisu.Header = su.Name;
                                tvise.Items.Add(tvisu);
                                tvisu.Tag = su.SubInfo;
                                tvisu.MouseDoubleClick += new MouseButtonEventHandler(subTVI_MouseDoubleClick);
                                tvisu.ToolTip = "Fai Doppio Click per scaricare il sottotitolo";
                            }
                            tvise.ItemContainerStyle = showsRoot.ItemContainerStyle;
                        }
                        tviv.ItemContainerStyle = showsRoot.ItemContainerStyle;
                        if (!tviv.HasItems) tvis.Items.Remove(tviv);
                    }
                    tvis.ItemContainerStyle = showsRoot.ItemContainerStyle;
                }
            }
        }

        private ContextMenu Show_ContextMenu(Show s)
        {
            ContextMenu cm = new ContextMenu();
            MenuItem mi1 = new MenuItem();
            mi1.Header = "Elimina";
            mi1.Click += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
            {
                MessageBoxResult mbr = MessageBox.Show("Conferma Eliminazione", "Procedere con l'eliminazione di" + s.Name + "?", MessageBoxButton.YesNo);
                if (mbr == MessageBoxResult.Yes)
                {
                    try
                    {
                        //CANCELLA SERIE
                    }
                    catch
                    {
                        Params.writeLog("Errore nell'eliminazione della serie " + s.Name);
                    }
                }
            });
            return cm;
        }

        

        void subTVI_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem su = (sender as TreeViewItem);
            if (su != null)
            {
                if (su.Tag != null) Params.dm.downloadSub(su.Tag as SubInfo);
            }
        }

        void seasonTVI_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem se = (sender as TreeViewItem);
            if (se != null)
            {
                foreach (TreeViewItem su in se.Items)
                {
                    if (su.Tag != null) Params.dm.downloadSub(su.Tag as SubInfo);
                }
            }
        }

        void versionTVI_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem v = (sender as TreeViewItem);
            if (v != null)
            {
                foreach (TreeViewItem se in v.Items)
                {
                    foreach (TreeViewItem su in se.Items)
                    {
                        if (su.Tag != null) Params.dm.downloadSub(su.Tag as SubInfo);
                    }
                }
            }
        }

        #endregion

        #region SEZIONE TAB MYSUBS

        private void updateMySubs()
        {
            if (firstUpdate) updateMySubs_first();
            else updateMySubs_last();
            Params.writeLog("mySubs caricato");
        }

        private void updateMySubs_last()
        {
            DateTime latest = DateTime.MinValue;
            if (Params.LastSubs == null) Params.LastSubs = new List<Sub>();
            else if (Params.LastSubs.Count > 0) latest = Params.LastSubs[0].SubmitDate;
            List<Sub> tmp = new List<Sub>();
            bool end = false;
            int page, morepage;
            page = 1;
            morepage = 1;
            List<Sub> nls = new List<Sub>();
            while (morepage > 0 && !end)
            {
                morepage = ITASA_API.favLastSubs(nls, Params.user, page);
                foreach (Sub s in nls)
                {
                    if (s.SubmitDate < latest)
                    {
                        end = true;
                    }
                    else
                    {
                        Show sh = Params.SearchShow(s.ShowID);
                        if (sh != null) sh.AddSub(s);
                    }
                }
                if (morepage < 0) morepage = 0;
                foreach (Sub s in nls)
                {
                    s.SubInfo = ITASA_API.subInfo(s.ID.ToString());
                }
                //AGGIORNA TAB DEI SUB
                nls.Sort();
                nls.Reverse();
                tmp.AddRange(nls);
                double p = (page * 100) / (morepage + page);
                page++;
                Params.Dispatch(this, updateProgressBar, p, "Ricezione dati sottotitoli serie preferite...");
            }
            tmp.AddRange(Params.LastSubs);
            Params.LastSubs = tmp;
            Params.Dispatch<Sub>(Params.mW, updateMySubsTab, Params.LastSubs);
        }

        private void updateMySubs_first()
        {
            if (Params.LastSubs == null) Params.LastSubs = new List<Sub>();
            int page, morepage;
            page = 1;
            morepage = 1;
            while (morepage > 0)
            {
                List<Sub> nls = new List<Sub>();
                morepage = ITASA_API.favLastSubs(nls, Params.user, page);
                foreach (Sub s in nls)
                {
                    Show sh = Params.SearchShow(s.ShowID);
                    if (sh != null) sh.AddSub(s);
                }
                if (morepage < 0) morepage = 0;
                foreach (Sub s in nls)
                {
                    s.SubInfo = ITASA_API.subInfo(s.ID.ToString());
                }
                //AGGIORNA TAB DEI SUB
                nls.Sort();
                nls.Reverse();
                Params.LastSubs.AddRange(nls);
                double p = (page * 100) / (morepage + page);
                page++;
                Params.Dispatch<Sub>(Params.mW, updateMySubsTab, nls);
                Params.Dispatch(this, updateProgressBar, p, "Ricezione dati sottotitoli serie preferite...");
            }
        }

        private void updateMySubsTab(List<Sub> ls)
        {
            if (ls != null)
            {
                Grid g = this.myITASA_griglia;
                foreach (Sub i in ls)
                {
                    RowDefinition rd = new RowDefinition();
                    rd.Height = GridLength.Auto;
                    g.RowDefinitions.Add(rd);
                    Sub_Label l = new Sub_Label(i);
                    Grid.SetColumn(l, 0);
                    l.label.Content = i.Name + " - " + i.Version;
                    Show s = Params.SearchShow(i.ShowID);
                    if (s != null) l.label.ToolTip = s.ToString();
                    else l.label.ToolTip = i.Name;
                    Control_Download cd = new Control_Download(i);
                    Grid.SetColumn(cd, 1);
                    Grid.SetRow(l, SubsRows);
                    Grid.SetRow(cd, SubsRows);
                    SubsRows++;
                    g.Children.Add(l);
                    g.Children.Add(cd);
                    if (SubsRows % 2 == 0) cd.Background = l.label.Background = new SolidColorBrush(Colors.White);
                    else cd.Background = l.label.Background = new SolidColorBrush(Colors.WhiteSmoke);
                }
            }
        }

        #endregion

        #region SEZIONE TAB ITASA RSS

        private void updateItasaRSS()
        {
            try
            {
                Params.ITASA = RSS_API.parseRSS(Config.ITASAurl);
            }
            catch (ArgumentException e)
            {
                Params.writeLog("URL ITASA RSS non valida: " + e.Message);
            }
            catch (WebException e)
            {
                Params.writeLog("URL ITASA RSS non valida: " + e.Message);
            }
            catch (XmlException e)
            {
                Params.writeLog("URL ITASA RSS non valida: " + e.Message);
            }
            catch (ThreadAbortException) { }
        }

        private void updateItasaRSSTab()
        {
            if (Params.ITASA != null)
            {
                Grid g = ITASA_griglia;
                Params.ITASA.Sort();
                Params.ITASA.Reverse();
                int c = 0;
                foreach (RSS_Sub i in Params.ITASA)
                {
                    RowDefinition rd = new RowDefinition();
                    rd.Height = GridLength.Auto;
                    g.RowDefinitions.Add(rd);
                    RSS_Sub_Label l = new RSS_Sub_Label(i);
                    Grid.SetColumn(l, 0);
                    l.label.Content = i.Title;
                    if (i.SubInfo != null)
                    {
                        Show s = Params.SearchShow(i.SubInfo.ShowID);
                        if (s != null) l.label.ToolTip = s.ToLabelString();
                        else l.label.ToolTip = i.SubInfo.ShowName;
                    }
                    else l.label.ToolTip = i.Title;
                    Control_Download cd = new Control_Download(i);
                    Grid.SetColumn(cd, 1);
                    Grid.SetRow(l, c);
                    Grid.SetRow(cd, c);
                    c++;
                    g.Children.Add(l);
                    g.Children.Add(cd);
                    if (c % 2 == 0) cd.Background = l.label.Background = new SolidColorBrush(Colors.White);
                    else cd.Background = l.label.Background = new SolidColorBrush(Colors.WhiteSmoke);
                }
                Params.writeLog("ITASA RSS caricato");
            }
        }

        private void dl_ITASA_Click(object sender, RoutedEventArgs e)
        {
            if (Params.ITASA != null)
            {
                foreach (RSS_Sub rs in Params.ITASA)
                {
                    Params.dm.downloadSub(rs.SubInfo);
                }
            }
        }

        #endregion

        #region SEZIONE TAB MYRSS

        private void updateMyRSS()
        {
            try
            {
                Params.myITASA = RSS_API.parseRSS(Config.myITASAurl);
            }
            catch (ArgumentException e)
            {
                Params.writeLog("URL myITASA RSS non valida: " + e.Message);
            }
            catch (WebException e)
            {
                Params.writeLog("URL myITASA RSS non valida: " + e.Message);
            }
            catch (XmlException e)
            {
                Params.writeLog("URL myITASA RSS non valida: " + e.Message);
            }
            catch (ThreadAbortException) { }
        }

        private void updateMyRSSTab()
        {
            if (Params.myITASA != null)
            {
                Grid g = myITASA_RSS_griglia;
                Params.myITASA.Sort();
                Params.myITASA.Reverse();
                int c = 0;
                foreach (RSS_Sub i in Params.myITASA)
                {
                    RowDefinition rd = new RowDefinition();
                    rd.Height = GridLength.Auto;
                    g.RowDefinitions.Add(rd);
                    RSS_Sub_Label l = new RSS_Sub_Label(i);
                    Grid.SetColumn(l, 0);
                    l.label.Content = i.Title;
                    if (i.SubInfo != null)
                    {
                        Show s = Params.SearchShow(i.SubInfo.ShowID);
                        if (s != null) l.label.ToolTip = s.ToLabelString();
                        else l.label.ToolTip = i.SubInfo.ShowName;
                    }
                    else l.label.ToolTip = i.Title;
                    Control_Download cd = new Control_Download(i);
                    Grid.SetColumn(cd, 1);
                    Grid.SetRow(l, c);
                    Grid.SetRow(cd, c);
                    c++;
                    g.Children.Add(l);
                    g.Children.Add(cd);
                    if (c % 2 == 0) cd.Background = l.label.Background = new SolidColorBrush(Colors.White);
                    else cd.Background = l.label.Background = new SolidColorBrush(Colors.WhiteSmoke);
                }
                Params.writeLog("myITASA RSS caricato");
            }
        }

        private void dl_myITASA_Click(object sender, RoutedEventArgs e)
        {
            if (Params.myITASA != null)
            {
                foreach (RSS_Sub rs in Params.myITASA)
                {
                    Params.dm.downloadSub(rs.SubInfo);
                }
            }
        }

        #endregion

        #region SEZIONE TAB CALENDARIO

        private void updateCalendarioXML()
        {
            try
            {
                Params.Episodes = ITASA_API.favNextEpisodes(Params.user);
                foreach (Show s in Params.Shows)
                {
                    if (s.LastEpisode.Date >= DateTime.Today.AddDays(-1)) Params.Episodes.Add(s.LastEpisode);
                }
                if (Params.Calendario == null) Params.Calendario = new Calendar(Params.user);
                Params.Calendario.update();
            }
            catch (ArgumentException e)
            {
                Params.writeLog("Errore nella creazione del calendario: " + e.Message);
            }
            catch (WebException e)
            {
                Params.writeLog("Errore nella creazione del calendario: " + e.Message);
            }
            catch (XmlException e)
            {
                Params.writeLog("Errore nella creazione del calendario: " + e.Message);
            }
        }

        private void updateCalendario()
        {
            if (Params.Episodes != null && Params.Calendario != null)
            {
                List<Episode_Date> lc = Params.Calendario.getList();
                Grid g = calendar_griglia;
                int c = 0;
                foreach (Episode_Date ed in lc)
                {
                    StackPanel sp = new StackPanel();
                    sp.Orientation = Orientation.Horizontal;
                    foreach (Episode i in ed.Episodes)
                    {
                        Label l = new Label();
                        l.Content = i.ShowName;
                        l.ToolTip = i.ToShortString();
                        sp.Children.Add(l);
                    }
                    RowDefinition rd = new RowDefinition();
                    rd.Height = GridLength.Auto;
                    g.RowDefinitions.Add(rd);
                    Label l1 = new Label();
                    Grid.SetColumn(l1, 0);
                    l1.Content = ed.Date.ToShortDateString();
                    Grid.SetColumn(sp, 1);
                    Grid.SetRow(l1, c);
                    Grid.SetRow(sp, c);
                    c++;
                    g.Children.Add(l1);
                    g.Children.Add(sp);
                    if (c % 2 == 0) l1.Background = sp.Background = new SolidColorBrush(Colors.White);
                    else l1.Background = sp.Background = new SolidColorBrush(Colors.WhiteSmoke);
                }
                Params.writeLog("Calendario caricato");
            }
        }

        #endregion

        #region SEZIONE TAB TORRENT

        private void updateTorrentXML()
        {
            if (Params.Shows != null)
            {
                List<Torrent_Show> lts = new List<Torrent_Show>();
                foreach (Show s in Params.Shows)
                {
                    if (s.Ended > DateTime.Now)
                    {
                        Torrent_Show ts = new Torrent_Show(s);
                        foreach (Itasa.API.Version v in s.Versions)
                        {
                            try
                            {
                                Torrent_Version eztv_tv = new Torrent_Version(v.VersionName + " EZTV", RSS_API.eztvRSS(s, v.VersionName));
                                ts.AddVersion(eztv_tv);
                                Torrent_Version isohunt_tv = new Torrent_Version(v.VersionName + " ISOHUNT", RSS_API.isohuntRSS(s, v.VersionName));
                                ts.AddVersion(isohunt_tv);
                                Torrent_Version isohunt_latest_tv = new Torrent_Version(v.VersionName + " Latest ISOHUNT", RSS_API.isohuntRSSLatest(s, v.VersionName));
                                ts.AddVersion(isohunt_latest_tv);
                            }
                            catch (ArgumentException e)
                            {
                                Params.writeLog("Errore nella ricerca di torrent per " + s.Name + " - " + v.VersionName + ": " + e.Message);
                            }
                            catch (WebException e)
                            {
                                Params.writeLog("Errore nella ricerca di torrent per " + s.Name + " - " + v.VersionName + ": " + e.Message);
                            }
                            catch (XmlException e)
                            {
                                Params.writeLog("Errore nella ricerca di torrent per " + s.Name + " - " + v.VersionName + ": " + e.Message);
                            }
                        }
                        if (ts.VersionList.Count > 0) lts.Add(ts);
                    }
                }
                Params.TorrentShows = lts;
            }
        }

        private void updateTorrentTab()
        {
            if (Params.TorrentShows != null)
            {
                this.Torrents_tc.Items.Clear();
                foreach (Torrent_Show s in Params.TorrentShows)
                {
                    this.Torrents_tc.Items.Add(new Torrent_Control(s));
                }
            }
            Params.writeLog("Torrent caricato");
        }

        #endregion

        private void update_Click(object sender, RoutedEventArgs e)
        {
            Params.updater.Interrupt();
        }

    }
}
